package cn.miao.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import static cn.miao.constants.MQConstant.*;

//rabbitMQ的配置
@Configuration
public class RabbitMQConfig {


    //定义交换机
    @Bean
    public Exchange exchangeNameTopic() {
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).durable(true).build();
    }

    //定义邮件的队列Bean
    @Bean
    public Queue emailQueue() {
        return new Queue(QUEUE_NAME_EMAIL, true);
    }


    //定义短信的队列Bean
    @Bean
    public Queue smsQueue() {
        return new Queue(QUEUE_NAME_SMS, true);
    }

    //定义系统消息的队列Bean
    @Bean
    public Queue systemMessageQueue() {
        return new Queue(QUEUE_NAME_SYSTEM_MESSAGE, true);
    }

    //定义短信的队列绑定到交换机
    @Bean
    public Binding smsQueueBinding() {

        // #.sms.course
        return BindingBuilder.bind(smsQueue()).to(exchangeNameTopic()).with("#.sms").noargs();

    }

    //定义邮件的队列绑定到交换机
    @Bean
    public Binding emailQueueBinding() {

        // #.email.course
        return BindingBuilder.bind(emailQueue()).to(exchangeNameTopic()).with("#.email").noargs();

    }

    @Bean
    public Binding systemMessageQueueBinding() {
        // #.systemmessage.course
        return BindingBuilder.bind(systemMessageQueue()).to(exchangeNameTopic()).with("#.message").noargs();

    }

    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);

        return rabbitTemplate;
    }
}